#include <iostream>
#include "progress_indicator.h"
#include "pg_copy_guard.h"
#include "pg_db_cursor.h"

using namespace std;

int main (int argc, char *argv[])
{
	//____________________________________________________________________________________
	// 		Connect to PostgreSQL
	//____________________________________________________________________________________
	string db_login = "dbname=test user=postgres host=fgu027";


	t_pg_cursor pg_db(db_login.c_str(), "panda_cursor");	//"dbname=all_vs_all_gene_bl2seq user=postgres"
	if ( pg_db.ConnectionBad() )
	{
		cerr	<< "\nERROR!! Connection to database ["
							<< db_login << "] failed.\n"
							<< pg_db.ErrorMessage() << "\n\n";
		return 1;
	}
    if( !pg_db.ExecCommandOk("CREATE TEMP TABLE t_1(AA integer, BB float8)"))
	{
		cerr		<< "ERROR!! PostgreSQL error : \n"
					<< pg_db.ErrorMessage() << "\n";
					return 1;
	}

    if( !pg_db.ExecCommandOk("insert into t_1 values(4,7.0);") ||
	   !pg_db.ExecCommandOk("insert into t_1 values(5,9.4);") )
	{
		cerr		<< "ERROR!! PostgreSQL error : \n"
					<< pg_db.ErrorMessage() << "\n";
					return 1;
	}

	cerr << "non-binary\n";
	// create binary cursor
	if (!pg_db.Declare("SELECT * from t_1", false))
		return pg_print_sql_err("create a cursor to retrieve values",
								pg_db,
								"SELECT * from t_1", cerr);
	
	{
		while (pg_db.Fetch(50))
		{
			int curr_batch_size = pg_db.Tuples();
			if (!curr_batch_size)
				break;
			for (int i = 0; i < curr_batch_size; ++i)
			{
				string AA = pg_db.getvalue(i, 0);
				string BB = pg_db.getvalue(i, 1);
				cerr << "AA=" << AA <<  "\t" << "AA=" << BB << "\n";
				
			}
		}
	}
	
	// close cursor
	if (!pg_db.Close())
		return pg_print_sql_err("close the  cursor for "
								"create a cursor to retrieve values",
								pg_db, "CLOSE CURSOR", cerr);
	
	cerr << "binary\n";
	// create binary cursor
	if (!pg_db.Declare("SELECT * from t_1", true))
		return pg_print_sql_err("create a cursor to retrieve values",
								pg_db,
								"SELECT * from t_1", cerr);
	
	{
		while (pg_db.Fetch(50))
		{
			int curr_batch_size = pg_db.Tuples();
			if (!curr_batch_size)
				break;
			for (int i = 0; i < curr_batch_size; ++i)
			{
				unsigned AA = pg_db.getvalue<unsigned>(i, 0);
				double BB = pg_db.getvalue<double>(i, 1);
				cerr << "AA=" << AA <<  "\t" << "AA=" << BB << "\n";
				
			}
		}
	}
	
	// close cursor
	if (!pg_db.Close())
		return pg_print_sql_err("close the  cursor for "
								"create a cursor to retrieve values",
								pg_db, "CLOSE CURSOR", cerr);
	

}

